#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
using System.IO;
using UnityEngine.Rendering;
using System.Collections;
using System.Reflection;

public class ScreenShot2 : EditorWindow
{
    private int width = 1920;
    private int height = 1080;
    private string fileName = "EditorScreenshot";
    private bool includeUI = false;
    
    [MenuItem("Tools/场景截图Post")]
    public static void ShowWindow()
    {
        GetWindow<ScreenShot2>("场景截图工具");
    }
    
    void OnGUI()
    {
        GUILayout.Label("截图设置", EditorStyles.boldLabel);
        width = EditorGUILayout.IntField("宽度", width);
        height = EditorGUILayout.IntField("高度", height);
        fileName = EditorGUILayout.TextField("文件名", fileName);
        includeUI = EditorGUILayout.Toggle("包含UI", includeUI);
        
        if (GUILayout.Button("捕获当前场景视图"))
        {
            // 使用协程确保正确渲染后处理效果
            EditorCoroutine.Start(CaptureSceneView());
        }
    }
    
    IEnumerator CaptureSceneView()
    {
        // 等待一帧确保场景完全渲染
        yield return null;
        
        SceneView sceneView = SceneView.lastActiveSceneView;
        if (sceneView == null)
        {
            Debug.LogError("没有找到活动的场景视图");
            yield break;
        }
        
        // 获取场景视图相机
        Camera sceneCam = sceneView.camera;
        if (sceneCam == null)
        {
            Debug.LogError("场景相机不存在");
            yield break;
        }
        
        // 创建临时相机来避免干扰场景视图
        GameObject tempCameraGO = new GameObject("TempScreenshotCamera");
        Camera tempCam = tempCameraGO.AddComponent<Camera>();
        tempCam.CopyFrom(sceneCam);
        
        // 设置相机位置和旋转
        tempCam.transform.position = sceneCam.transform.position;
        tempCam.transform.rotation = sceneCam.transform.rotation;
        
        // 创建渲染纹理 - 使用ARGB32格式确保兼容性
        RenderTexture rt = new RenderTexture(width, height, 24, RenderTextureFormat.ARGB32);
        rt.antiAliasing = 8; // 开启抗锯齿
        
        // 设置目标纹理
        tempCam.targetTexture = rt;
        
        // 处理后处理效果
        bool isURP = GraphicsSettings.currentRenderPipeline?.GetType().Name.Contains("Universal") ?? false;
        bool isHDRP = GraphicsSettings.currentRenderPipeline?.GetType().Name.Contains("HighDefinition") ?? false;
        
        // 强制重绘场景
        sceneView.Repaint();
        
        // 等待渲染完成
        yield return null;
        yield return new WaitForEndOfFrame();
        
        // 渲染到纹理 - 使用反射方法确保后处理效果被应用
        if (isURP || isHDRP)
        {
            // 使用反射调用URP/HDRP的渲染方法
            RenderWithReflection(tempCam);
        }
        else
        {
            // 内置渲染管线
            tempCam.Render();
        }
        
        // 再次等待确保渲染完成
        yield return null;
        
        // 读取像素
        RenderTexture.active = rt;
        Texture2D tex = new Texture2D(width, height, TextureFormat.ARGB32, false);
        tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
        tex.Apply();
        
        // 保存文件
        byte[] bytes = tex.EncodeToPNG();
        string path = EditorUtility.SaveFilePanel("保存截图", "", fileName, "png");
        if (!string.IsNullOrEmpty(path))
        {
            File.WriteAllBytes(path, bytes);
            Debug.Log($"场景截图已保存: {path}");
            EditorUtility.RevealInFinder(path);
        }
        
        // 清理
        RenderTexture.active = null;
        DestroyImmediate(rt);
        DestroyImmediate(tex);
        DestroyImmediate(tempCameraGO);
        
        // 刷新资源视图
        AssetDatabase.Refresh();
    }
    
    // 使用反射调用SRP渲染方法（支持URP和HDRP）
    private void RenderWithReflection(Camera camera)
    {
        // 获取当前渲染管线类型
        var pipelineType = GraphicsSettings.currentRenderPipeline?.GetType();
        
        if (pipelineType == null) 
        {
            camera.Render();
            return;
        }
        
        try
        {
            // 尝试调用URP的渲染方法
            if (pipelineType.Name.Contains("Universal"))
            {
                // 获取UniversalRenderPipeline类型
                var urpType = pipelineType.Assembly.GetType("UnityEngine.Rendering.Universal.UniversalRenderPipeline");
                if (urpType != null)
                {
                    // 获取RenderSingleCamera方法
                    MethodInfo renderMethod = urpType.GetMethod("RenderSingleCamera", 
                        BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public, 
                        null, 
                        new[] { typeof(ScriptableRenderContext), typeof(Camera) }, 
                        null);
                    
                    if (renderMethod != null)
                    {
                        // 创建ScriptableRenderContext
                        var contextType = typeof(ScriptableRenderContext);
                        object context = System.Activator.CreateInstance(contextType);
                        
                        // 调用方法
                        renderMethod.Invoke(null, new object[] { context, camera });
                        return;
                    }
                }
            }
            
            // 尝试调用HDRP的渲染方法
            if (pipelineType.Name.Contains("HighDefinition"))
            {
                // 获取HDRenderPipeline类型
                var hdrpType = pipelineType.Assembly.GetType("UnityEngine.Rendering.HighDefinition.HDRenderPipeline");
                if (hdrpType != null)
                {
                    // 获取RenderCamera方法
                    MethodInfo renderMethod = hdrpType.GetMethod("RenderCamera", 
                        BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public, 
                        null, 
                        new[] { typeof(ScriptableRenderContext), typeof(Camera) }, 
                        null);
                    
                    if (renderMethod != null)
                    {
                        // 创建ScriptableRenderContext
                        var contextType = typeof(ScriptableRenderContext);
                        object context = System.Activator.CreateInstance(contextType);
                        
                        // 调用方法
                        renderMethod.Invoke(null, new object[] { context, camera });
                        return;
                    }
                }
            }
            
            // 回退到标准渲染方法
            camera.Render();
        }
        catch (System.Exception ex)
        {
            Debug.LogError($"渲染失败: {ex.Message}");
            camera.Render();
        }
    }
}

// 用于在编辑器中运行协程的辅助类
public class EditorCoroutine
{
    public static void Start(IEnumerator routine)
    {
        EditorCoroutineRunner runner = new EditorCoroutineRunner(routine);
        runner.Start();
    }

    private class EditorCoroutineRunner
    {
        private readonly IEnumerator routine;
        public EditorCoroutineRunner(IEnumerator routine) => this.routine = routine;
        public void Start() => EditorApplication.update += Update;
        private void Update()
        {
            if (!routine.MoveNext())
            {
                EditorApplication.update -= Update;
            }
        }
    }
}
#endif
